package com.yf.service.impl;

import com.yf.consts.Const;
import com.yf.dao.UserDao;
import com.yf.entity.LevelEntity;
import com.yf.entity.UserEntity;
import com.yf.entity.UserRelation;
import com.yf.entity.WxUser;
import com.yf.enums.UserStatusEnum;
import com.yf.response.RRException;
import com.yf.service.LevelService;
import com.yf.service.UserService;
import com.yf.service.WxWebService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 用户Service实现类
 *
 * @author hxf
 * @email 505860922@qq.com
 * @date Thu Aug 16 13:36:44 CST 2018
 */
@Service
@Slf4j
public class UserServiceImpl extends BaseServiceImpl<UserEntity> implements UserService {
    @Autowired
    private UserDao userDao;


    /**内部方法**/

    /**
     * 是否是系统虚拟用户
     * @param userEntity
     * @return
     */
    private boolean isAdminUser(UserEntity userEntity){
        if(userEntity.getId().equals(Const.ADMIN_USER_ID)){
            return true;
        }
        return false;
    }

    /**
     * 更换上级 更换路径 以及下面的路径
     * @param entity
     * @param parent
     */
    @Transactional
    public void updateParent(UserEntity entity,UserEntity parent){
        String oldPath = getPath(entity);
        entity.setParentId(parent.getId());
        entity.setPath(getPath(parent));
        String newPath = getPath(entity);
        //保存当前用户
        userDao.update(entity);
        //更新下级路径
        userDao.updateDownPath(oldPath,newPath);
    }

    /**
     * 获取user1跟user2的关系
     *
     * @return
     */
    private UserRelation getRelation(UserEntity user1, UserEntity user2){
        if(isAdminUser(user1)) {
            return new UserRelation(true,false,true);
        }
        if(isAdminUser(user2)) {
            return new UserRelation(false,true,true);
        }
        if(user1.getPath().contains(user2.getPath())){
            return new UserRelation(false,true,true);
        }
        if(user2.getPath().contains(user1.getPath())){
            return new UserRelation(true,false,true);
        }
        return new UserRelation(false,false,false);
    }



    /**
     * TODO
     * 创建系统编号
     *
     * @return
     */
    private String createCode() {
        return "";
    }

    /**
     * 初始化游客的初始化参数
     *
     * @param userEntity
     * @return
     */
    private UserEntity initVistor(WxUser wxUser, UserEntity parent) {
        if (parent == null) {
            throw new RRException("所填写的推荐人不存在!");
        }
        //初始化注册、级别修改、登录时间
        Date date = new Date();
        //初始化级别
        LevelEntity level = levelService.getInitUserLevel();
        //构造游客
        UserEntity userEntity = new UserEntity(level.getId(),wxUser.getNickName(), wxUser.getHeadImgUrl(), wxUser.getSex(), wxUser.getOpenId(), wxUser.getUnionId(), parent.getTeam(), parent.getId(), date, date, date, UserStatusEnum.ACTIVE.getState(), getPath(parent));
        userDao.save(userEntity);
        return userEntity;
    }

    private String getPath(UserEntity parent){
        if(parent.getPath() == null){
            return String.valueOf(parent.getId());
        }
        return parent.getPath()+"/"+parent.getId();
    }




    /**
     * 外部方法实现
     **/

    @Override
    public void validateLogin(UserEntity userEntity) {
        if (userEntity == null) {
            throw new RRException("账户不存在!");
        }
        if (!userEntity.getStatus().equals(UserStatusEnum.ACTIVE.getState())) {
            throw new RRException("用户没有激活!");
        }
    }

    @Override
    public UserEntity findByUnionId(String unionId) {
        List<UserEntity> list = userDao.findByUnionId(unionId);
        if (list == null) {
            return null;
        }
        if (list.size() > 1) {
            log.error("账号异常unionId不唯一:" + unionId);
            throw new RRException(unionId + "账号不唯一");
        }
        return list.get(0);
    }

    @Override
    public UserEntity findByOpenid(String openId) {
        List<UserEntity> list = userDao.findByOpenId(openId);
        if (list == null) {
            return null;
        }
        if (list.size() > 1) {
            log.error("账号异常openId不唯一:" + openId);
            throw new RRException(openId + "账号不唯一");
        }
        return list.get(0);
    }

    @Override
    public UserEntity findByPhone(String phone) {
        List<UserEntity> list = userDao.findByPhone(phone);
        if (list == null) {
            return null;
        }
        if (list.size() > 1) {
            throw new RRException("账户异常Phone不唯一:" + phone);
        }
        return list.get(0);
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserEntity registerVistor(WxUser wxUser, Long parentId) {
        UserEntity parent = get(parentId);
        UserEntity userEntity = initVistor(wxUser, parent);//初始化
        return userEntity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserEntity registerVistor(WxUser wxUser, String phone) {
        UserEntity parent = findByPhone(phone);
        UserEntity userEntity = initVistor(wxUser, parent);//初始化
        return userEntity;
    }

    @Override
    public UserEntity completeUserInfo(UserEntity userEntity) {
        return null;
    }

    @Override
    public UserEntity updateUserInfo(UserEntity userEntity) {
        return null;
    }

    @Override
    public List<UserEntity> findDownByTree(UserEntity userEntity) {
        return userDao.findDownByTree(userEntity.getPath());
    }

    @Override
    public List<UserEntity> findUpByTree(UserEntity userEntity) {
        return userDao.findUpByTree(userEntity.getPath().split("/"));
    }

    @Override
    public List<UserEntity> findDown(UserEntity userEntity) {
        return userDao.findDown(userEntity.getId());
    }

    @Override
    @Transactional
    public UserEntity createTreeUser(UserEntity parent) {
        UserEntity userEntity = new UserEntity();
        userEntity.setPath(getPath(parent));
        userDao.save(userEntity);
        return userEntity;
    }

    @Autowired
    private LevelService levelService;

    @Autowired
    private WxWebService wxWebService;


}
